<template>
	<view class="ingame">
		<view class="header">
			<view class="title" :style="{ top: globalData.statusBarHeight + 'px', height: globalData.toBar + 'px', lineHeight: globalData.toBar + 'px' }">
				<uni-nav-bar color="#fff" backgroundColor="transparent" title="单词消消乐" left-icon="left" @clickLeft="goback" />
			</view>
			<view class="header-content"></view>
		</view>
		<view class="content" :style="{ height: contentHeight, top: globalData.statusBarHeight + globalData.toBar + 'px', bottom: '20rpx' }">
			<view class="game-header">
				<h3>第{{ num }}关</h3>
				<view class="timer">{{ timer }}</view>
				<view class="frequency">
					剩余
					<span style="color: #fe8926">{{ remain }}</span>
					次
				</view>
			</view>
			<view class="game-main">
				<view class="game-container" style="background-color: #ffff">
					<template v-for="(word, index) in shuffledWords">
						<view :key="index" :class="['word-item', { green: checkedWords.includes(word.content) }]" v-if="word.isShow" @click="save(word, index)">
							{{ extractContentAfterPrefix(word.content) }}
						</view>
					</template>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import { getWords, postSubmit, getremain } from '@/services/level.js';
import { getChuangWords } from '@/services/wordbreak.js';
import md5 from 'js-md5';
import CrypotJS from 'crypto-js';
import { decryptAES, encryptAES } from '@/js/common.js';

export default {
	data() {
		return {
			globalData: null,
			contentHeight: 0,
			wordDta: {},
			shuffledPairs: [],
			chineseWords: [],
			englishWords: [],
			shuffledWords: [],

			checkedWords: [],
			totalMilliseconds: 0,
			timer: '',
			timeTotal: 0,
			countdownInterval: null,
			stage: 0,
			libId: 0,
			num: 1,
			innerAudioContext: null,
			innerAudioContexts: null,
			remain: '',
			limitTime: 60000,
			type: 1,
			pass: false
		};
	},
	created() {
		// 在组件创建时获取 globalData

		try {
			this.globalData = wx.getStorageSync('globalData');
			this.calculateContentHeight();
		} catch (error) {
			// 处理获取存储失败的情况
			console.error('Failed to get globalData from storage:', error);
		}
	},
	onLoad(options) {
		if (options.type) {
			//传了type表示是从闯关活动进的
			this.getChuangWordsData();
			this.type = 2;
		} else {
			let item = JSON.parse(options.item);
			this.stage = item.rid;
			this.num = item.stage;
			this.libId = item.libId;
			this.limitTime = item.limitTime;
			this.getWordsData({ stage: item.stage, libId: item.libId });
		}
		this.getremainData();
	},
	computed: {
		isFinish() {
			return this.shuffledWords.every((word) => !word.isShow);
		}
	},
	watch: {
		// 监听 isFinish 的变化
		isFinish(newVal) {
			// 如果 isFinish 变为 true，则执行跳转
			if (newVal) {
				this.pass = true;
				this.assemblyData();
			}
		}
	},

	beforeDestroy() {
		if (this.countdownInterval) {
			clearInterval(this.countdownInterval);
			this.countdownInterval = null;
		}

		// 停止音频播放
		if (this.innerAudioContext) {
			this.innerAudioContext.stop();
		}
		// 销毁音频上下文
		this.innerAudioContext = null;
		if (this.innerAudioContexts) {
			this.innerAudioContexts.stop();
		}
		// 销毁音频上下文
		this.innerAudioContexts = null;
	},
	methods: {
		async getChuangWordsData() {
			const res = await getChuangWords();
			if (res.code == 200) {
				let words = decryptAES(res.data.data.content);
				this.stage = res.data.stageRid;
				this.num = res.data.stage;
				this.libId = res.data.libId;
				this.wordDta = JSON.parse(words);
				this.parseAndShuffle();
				this.startCountdown(this.limitTime);
				this.checkedpalyVoicebgi('https://manage.aikoolearn.com/video-api/profile/upload/common/WXAPP/mp3/bgi.mp3');
			} else {
				wx.showToast({
					title: res.msg,
					icon: 'none',
					duration: 2000
				});

				setTimeout(() => {
					wx.navigateBack();
				}, 1000);
			}
		},
		removeFirstProperty(obj) {
			const keys = Object.keys(obj);
			if (keys.length > 0) {
				const firstKey = keys[0];
				const { [firstKey]: removed, ...rest } = obj;
				return rest;
			}
			return obj; // 如果没有属性可以删除，返回原对象
		},

		async getremainData() {
			const res = await getremain();
			if (res.code == 200) {
				this.remain = res.data;
			}
		},

		//计时
		startCountdown(time) {
			this.timeTotal = time;
			this.totalMilliseconds = time; // 初始总毫秒数
			this.timer = (this.totalMilliseconds / 1000).toFixed(1) + 's'; // 初始化倒计时显示
			this.countdownInterval = setInterval(() => {
				this.totalMilliseconds -= 100; // 每次间隔减少1000毫秒
				let remainingSeconds = this.totalMilliseconds / 1000; // 剩余秒数
				this.timer = remainingSeconds.toFixed(1) + 's'; // 更新倒计时显示，保留一位小数
				if (this.totalMilliseconds > 0) {
					// 更新视图或其他相关操作
				} else {
					clearInterval(this.countdownInterval);
					const firstKey = Object.keys(this.wordDta)[0];

					// 使用该键获取对应的值
					const firstValue = this.wordDta[firstKey];

					let obj = {};
					obj[firstKey] = firstValue;
					console.log(obj, 'obj');
					this.assemblyData(obj);

					// 这里可以添加倒计时结束后的处理逻辑
				}
			}, 100);
		},
		objectToMap(obj) {
			return new Map(Object.entries(obj));
		},
		extractContentAfterPrefix(str) {
			// 查找第一个空格或点号的位置，这将是前缀的结束位置
			const prefixEndIndex = str.search(/[ .]/);
			if (prefixEndIndex === -1) {
				// 如果没有找到空格或点号，返回整个字符串（假设整个字符串就是需要的内容）
				return str.trim();
			}

			// 截取前缀之后的部分
			const content = str.substring(prefixEndIndex + 1).trim();

			// 定义可能的分隔符
			const separators = [';', ',', ' '];

			// 查找第一个分隔符的位置
			const terminatorIndex = separators.find((separator) => content.indexOf(separator) !== -1) ? content.search(new RegExp(separators.join('|'))) : content.length; // 如果没有找到分隔符，则默认为字符串末尾

			// 返回前缀之后、第一个分隔符之前的内容
			return content.substring(0, terminatorIndex);
		},
		//获取闯关内容
		async getWordsData(data) {
			const res = await getWords(data);
			if (res.code == 200) {
				let words = decryptAES(res.data.content);
				this.wordDta = JSON.parse(words);
				this.parseAndShuffle();
				this.startCountdown(this.limitTime);
				this.checkedpalyVoicebgi('https://manage.aikoolearn.com/video-api/profile/upload/common/WXAPP/mp3/bgi.mp3');
			} else {
				wx.showToast({
					title: res.msg,
					icon: 'none',
					duration: 2000
				});

				setTimeout(() => {
					wx.navigateBack();
				}, 1000);
			}
		},
		async postSubmitData(data) {
			console.log(data, 'data');
			const res = await postSubmit(data);
			if (res.code == 200) {
				wx.redirectTo({
					url:
						'/pages/ingame/successful?type=1' +
						'&isgame=' +
						this.type +
						'&timer=' +
						res.data.cost +
						'&stage=' +
						this.stage +
						'&libId=' +
						this.libId +
						'&stageid=' +
						this.num
				});
			} else if (res.code == 500) {
				uni.redirectTo({
					url: '/pages/ingame/successful?type=0' + '&isgame=' + this.type + '&stage=' + this.stage + '&libId=' + this.libId + '&stageid=' + this.num
				});
			} else {
				wx.showToast({
					title: res.msg,
					icon: 'none',
					duration: 2000
				});
				setTimeout(() => {
					wx.navigateBack();
				}, 1000);
			}
		},
		//组装提交的信息sign
		mapToMd5(map) {
			// 将Map对象转换为一个有序的键值对数组
			const entries = map.entries();
			// 遍历数组并创建一个可预测的字符串表示形式
			let str = '';
			for (const [key, value] of entries) {
				str += key + ':' + value + ';';
			}
			// 计算字符串的MD5哈希值

			return str;
		},
		assemblyData(data) {
			let clientTime = new Date().getTime();
			let cost = this.timeTotal - this.totalMilliseconds;
			let stage = this.stage;
			console.log(this.pass, 'pass');
			let jsonString = !this.pass ? this.objectToMap(data) : this.objectToMap(this.wordDta); //转为有序字典
			let obj = JSON.stringify(Object.fromEntries(jsonString));
			let result = md5(obj);
			const submitResult = stage + result + clientTime + cost;
			//ase加密\
			let sign = md5(encryptAES(submitResult));
			this.postSubmitData({ clientTime, cost, result, stage, sign });
		},

		//选择了方块
		save(item, index) {
			if (this.checkedWords.length) {
				if (this.wordDta[this.checkedWords[0]] == item.content || this.wordDta[item.content] === this.checkedWords[0]) {
					this.checkedWords.push(item.content);
					this.shuffledWords.forEach((word) => {
						if (this.checkedWords.includes(word.content)) {
							word.isShow = false;
							// 如果需要，可以在这里播放消除声音
							this.checkedpalyVoice('https://manage.aikoolearn.com/video-api/profile/upload/common/WXAPP/mp3/eliminate.wav');
						}
					});
				} else {
					//匹配失败

					wx.vibrateShort({
						type: 'heavy'
					});
				}
				this.checkedWords = [];
			} else {
				this.checkedpalyVoice('https://manage.aikoolearn.com/video-api/profile/upload/common/WXAPP/mp3/click.mp3');
				//选中第一个的时候
				this.checkedWords.push(item.content);
			}
		},
		shuffleArray(array) {
			for (let i = array.length - 1; i > 0; i--) {
				const j = Math.floor(Math.random() * (i + 1));
				[array[i], array[j]] = [array[j], array[i]];
			}
		},
		parseAndShuffle() {
			try {
				this.chineseWords = Object.values(this.wordDta);
				this.englishWords = Object.keys(this.wordDta);
				let allWord = [...this.chineseWords, ...this.englishWords];
				this.shuffleArray(allWord);
				this.shuffledWords = allWord.map((item) => ({ content: item, isShow: true }));
			} catch (error) {
				console.error('Error parsing content:', error);
			}
		},
		checkedpalyVoice(url) {
			// 如果页面已经有一个音频上下文，则先停止它
			if (this.innerAudioContext) {
				this.innerAudioContext.stop();
			}
			// 创建新的音频上下文
			this.innerAudioContext = wx.createInnerAudioContext();
			this.innerAudioContext.autoplay = false;
			this.innerAudioContext.loop = false;
			// 设置音频选项
			wx.setInnerAudioOption({
				obeyMuteSwitch: false,
				success: function (e) {},
				fail: function (e) {}
			});
			this.innerAudioContext.src = url;
			this.innerAudioContext.play();
		},
		checkedpalyVoicebgi(url) {
			// 如果页面已经有一个音频上下文，则先停止它
			if (this.innerAudioContexts) {
				this.innerAudioContexts.stop();
			}
			// 创建新的音频上下文
			this.innerAudioContexts = wx.createInnerAudioContext();
			this.innerAudioContexts.autoplay = false;
			this.innerAudioContexts.loop = false;
			// 设置音频选项
			wx.setInnerAudioOption({
				obeyMuteSwitch: false,
				success: function (e) {},
				fail: function (e) {}
			});
			this.innerAudioContexts.src = url;
			this.innerAudioContexts.play();
		},
		goback() {
			uni.navigateBack();
		},
		calculateContentHeight() {
			const statusBarHeight = this.globalData.statusBarHeight;
			const toBarHeight = this.globalData.toBar;
			const additionalHeight = 70; // 额外的 60px

			// 计算内容高度
			const contentHeight = `calc(100vh - (${statusBarHeight}px + ${toBarHeight}px + ${additionalHeight}px))`;

			this.contentHeight = contentHeight;
		}
	}
};
</script>

<style scoped lang="scss">
.ingame {
	height: 100vh;
	position: relative;
	background-color: #f0f2f5;
	.header {
		width: 100%;
		height: 400rpx;
		background: linear-gradient(270deg, #05d19a 0%, #05c7ac 100%);
		border-radius: 0rpx 0rpx 40rpx 40rpx;
		overflow: hidden;
		.status_bar {
			height: var(--status-bar-height);
			width: 100%;
		}
		.title {
			position: absolute;
			width: 100%;
			left: 50%;
			/* top: 20px; */
			transform: translate(-50%, 0);
			color: white;
			font-size: 32rpx;
		}
	}

	.content {
		position: absolute;
		.game-header {
			width: 702rpx;
			height: 160rpx;
			transform: translate(3%, 0);
			background: linear-gradient(180deg, #82e0d3 0%, #e8fada 67%, #fae3a7 100%);
			border-radius: 32rpx 32rpx 0rpx 0rpx;
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 0 24rpx;
			box-sizing: border-box;
			h3 {
				font-size: 30rpx;
			}
			.frequency {
				color: #666666;
				font-size: 28rpx;
			}
			.timer {
				width: 142rpx;
				height: 60rpx;
				color: #fff;
				text-align: center;
				line-height: 60rpx;
				background: #fe8926;
				box-shadow: 0rpx 8rpx 20rpx 0rpx rgba(254, 137, 38, 0.4);
				border-radius: 30rpx;
			}
		}
		.game-main {
			width: 702rpx;
			height: calc(100vh - 400rpx);
			overflow-y: scroll;
			transform: translate(3%, 0);
			background-color: #fff;
			border-radius: 32rpx;
			position: absolute;
			top: 131.679rpx;
			padding: 32rpx;
			padding-bottom: 50rpx;
			box-sizing: border-box;
			.game-container {
				box-sizing: border-box;
				display: grid;
				transform: translate(0%, 0);
				grid-template-columns: repeat(3, 1fr); /* 创建三列，每列占据相等的空间 */
				grid-gap: 5px; /* 列与列之间的间隙 */
			}
			.word-item {
				font-size: 26rpx;
				white-space: normal;
				background: #edeff2;
				padding: 24rpx 20rpx;
				border-radius: 16rpx;
				text-align: center;
				margin: 10rpx;
				min-height: 50rpx;
				display: flex;
				align-items: center;
				justify-content: center;
			}
		}
	}

	.hidden {
		visibility: hidden;
		pointer-events: none; /* 阻止用户与不可见的单词交互 */
		// transition: visibility 0.5s ease-in-out;
	}

	.green {
		background: linear-gradient(270deg, #05d19a 0%, #05c7ac 100%) !important;
		border-radius: 16rpx;
		color: #fff;
	}
	::v-deep {
		.uni-navbar--border {
			border-bottom-color: transparent !important;
		}
	}
}
</style>
